/**
* 、单词跟读练习页面
*/
<template>
	<view class="practice" :style="{height:pageHeight}">
		<!--
		 indicator-dots 是否显示面板指示点
		 circular 是否采用衔接滑动，即播放到末尾后重新回到开头
		 autoplay 是否自动切换
		 interval 自动切换时间间隔
		 -->
		<view class="practice-hearde">
			<view class="flex" style="justify-content: space-between;align-items: center;">
				<view>{{formattedTime}}</view>
				<button class=" cu-btn bg-primary text-white " @click="toPages">保存</button>
			</view>
			<u-row :gutter="12">
				<u-col :span="4">
					<u-icon name="arrow-left" size="28" @click="jian"></u-icon>
				</u-col>
				<u-col :span="4">
					<view class="flex " style="justify-content: center;align-items: center;">
						<text>{{current + 1}}/10</text>
					</view>
				</u-col>
				<u-col :span="4">
					<view class="flex" style="justify-content: flex-end;align-items: center;">
						<u-icon name="arrow-right" size="28" @click="add"></u-icon>
					</view>

				</u-col>
			</u-row>
		</view>
		<swiper :style="{height:itemHeight}" class="swiper" :circular="false" :indicator-dots="false" :autoplay="false"
			:interval="interval" :duration="duration" @change="handlerChange" :current="current">
			<swiper-item class="item" v-for="item in rowList" :key="item.value">
				<practiceItem :itemHeight="itemHeight" :item="item" @status="handlerStatus"></practiceItem>
			</swiper-item>
		</swiper>
	</view>
</template>

<script setup>
	import practiceItem from './components/practice-item.vue';
	import {
		getCurrentInstance,
		ref
	} from 'vue';

	// 引入小程序的生命周期函数
	import {
		onReady,
		onLoad
	} from '@dcloudio/uni-app'
	import {
		toast
	} from 'luoyu-uni-utils';
	import {
		speechToText
	} from '@/api/luoyu';
	import {
		getEnglishList
	} from '@/api/english-static.js'
	import {
		tansParams
	} from 'luoyu-uni-utils'
	import {
		showConfirm
	} from 'luoyu-uni-utils';
	//获取页面的高度
	const pageHeight = ref('100%')
	const itemHeight = ref('100%')

	const instance = getCurrentInstance()
	const current = ref(0)
	const rowList = ref([])

	//页面渲染完成时调用
	onReady(() => {
		const query = uni.createSelectorQuery().in(instance)
		query.select('.practice-hearde').boundingClientRect((res) => {
			const windowHeight = (uni.getSystemInfoSync().windowHeight)
			pageHeight.value = windowHeight + 'px'
			itemHeight.value = (windowHeight - res.height) + 'px'
		}).exec()
	})
	//根据之后添加的状态列表
	const statusList = ref([])
	//获取跟读识别状态
	const handlerStatus = (event) => {
		const {
			item
		} = event
		const targetIndex = statusList.value.findIndex(i => item.label == item.label)
		if (targetIndex != -1) {
			statusList.value[targetIndex] = {
				...item,
				statusFlag: event.statusFlag
			}
		} else {
			statusList.value.push({
				...item,
				statusFlag: event.statusFlag
			})
		}

	}
	const getList = async (pageNum = 1) => {
		const res = await getEnglishList(null, pageNum, 10)
		console.log(res, 'res');
		rowList.value = res.rows
		//获取数据成功然后就开始计时、
		start()
	}

	function handlerChange(event) {
		current.value = event.detail.current
	}

	function toPages() {
		const title = statusList.value >= 9 ? '当前题目已答完' : '当前题目未答完，是否提交'
		showConfirm(title, "提示").then(() => {
			//获取结束的时间
			stop()
			//算得的分数
			let feshu = `${statusList.value.length}0` 
			//用的时间
			const time = formattedTime.value
			//所得的积分
			let points = 0
			if(parseInt(feshu) >0 ) {
				points = calculatePoints(parseInt(feshu))
			}
			const params = tansParams({
				feshu,
				time,
				points
			})
			uni.navigateTo({
				url: '/pages_word_follow-up/pages/points/points-collection?' + params
			})
		})

	}

	function add() {
		if (current.value < 9) {
			current.value++
		}
	}

	function jian() {
		if (current.value >= 1) {
			current.value--
		}
	}
	/**
	 * 构建所得分数对应的积分
	 * @param {Object} score 分数
	 */
	function calculatePoints(score) {
		let points = 0;
		if (score >= 90 && score <= 100) {
			points = 2; // 90 到 100 分之间
		} else if (score >= 70 && score < 80) {
			points = 1.5; // 70 到 80 分之间
		} else if (score >= 50 && score < 60) {
			points = 1; // 50 到 60 分之间
		} else if (score < 50) {
			// 50 分以下，返回 0.1 到 1 之间的随机积分
			points = (Math.random() * (1 - 0.1) + 0.1).toFixed(2); // 随机生成 0.1 到 1 之间的小数
		}
		return points;
	}

	//当前的时间
	const startTime = Date.now();
	// 格式化时间
	const formattedTime = ref('')
	let timerId = null; // 用于保存定时器ID
	let isRunning = true; // 控制定时器是否运行
	// 定时器函数，每秒更新一次
	function startTimer() {
		if (!isRunning) return; // 如果定时器不再运行，则直接返回
		// 获取当前时间
		let currentTime = Date.now();
		// 计算经过的时间（毫秒）
		let elapsedTime = currentTime - startTime;
		// 将经过的时间转换为秒
		let elapsedSeconds = Math.floor(elapsedTime / 1000);
		// 转换为小时、分钟和秒
		let hours = String(Math.floor(elapsedSeconds / 3600)).padStart(2, '0');
		let minutes = String(Math.floor((elapsedSeconds % 3600) / 60)).padStart(2, '0');
		let seconds = String(elapsedSeconds % 60).padStart(2, '0');
		// 格式化时间
		formattedTime.value = `${hours}:${minutes}:${seconds}`;
		// 显示时间（这里使用 console.log，你可以根据需要替换为其他显示方式）
		// console.log(formattedTime.value);
		// 设置下一个定时器调用，并保存ID
		timerId = setTimeout(startTimer, 1000);
	}
	// 开始定时器
	function start() {
		isRunning = true;
		startTimer();
	}
	// 停止定时器
	function stop() {
		isRunning = false;
		if (timerId !== null) {
			clearTimeout(timerId); // 取消定时器
			timerId = null; // 重置定时器ID
		}
	}
	//页面初始化完成时调用	
	onLoad((query) => {
		const index = query.index || 1
		getList(index)
	})
</script>

<style scoped lang="scss">
	.practice {
		position: relative;
		height: 100%;

		.practice-hearde {
			width: 750rpx;
			height: 85px;
			padding: 10px;
			box-sizing: border-box;
		}

		.swiper {
			width: 750rpx;
			height: 100%;

			.item {
				width: 750rpx;
			}
		}
	}
</style>